package org.mozhu.mboot.core.web.freemarker;

import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.TemplateHashModel;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class FreeMarkerStaticModelRegistry {

    private Map<String, Object> staticModels = new HashMap<>();

    public Map<String, Object> getStaticModels() {
        return staticModels;
    }

    public void register(Class<?> clazz) {
        register(clazz.getSimpleName(), clazz);
    }

    public void register(String name, Class<?> clazz) {
        staticModels.put(name, staticModel(clazz.getCanonicalName()));
    }

    private Object staticModel(String s) {
        try {
            BeansWrapperBuilder builder = new BeansWrapperBuilder(Configuration.VERSION_2_3_28);
            builder.setUseModelCache(false);
            builder.setExposeFields(false);

            BeansWrapper wrapper = builder.build();
            TemplateHashModel staticModels = wrapper.getStaticModels();
            TemplateHashModel fileStatics = (TemplateHashModel) staticModels.get(s);
            return fileStatics;
        } catch (Exception e) {
            log.error("Create freeMarker hash model failed", e);
            throw new IllegalStateException("Create freeMarker hash model failed", e);
        }
    }

}
